package com.example.tangyee.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.bean.BloodGlucoseRecord;
import com.example.tangyee.utils.BloodGlucoseDataUtil;
import com.example.tangyee.utils.DateUtils;
import com.example.tangyee.utils.DensityUtils;
import com.example.tangyee.view.BarChartView;
import com.example.tangyee.view.MyPopup;
import com.example.tangyee.view.OnItemClickedListener;
import com.lxj.xpopup.XPopup;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class BloodGlucoseActivity extends AppCompatActivity {

    private static final String TAG = "BloodGlucoseActivity";

    private Unbinder mUnbinder;

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.top_title)
    TextView title;

    @BindView(R.id.bar_chart)
    BarChartView mBarChartView;

    @BindView(R.id.loading_view)
    View loadingView;

    @BindView(R.id.blood_glucose_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.recycler_view_card)
    CardView mCardView;

    private int days = 100;
    private BloodGlucoseDataUtil mDataUtil = new BloodGlucoseDataUtil();
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("MM月dd日", Locale.CHINA);

    int low = 0, good = 0, high = 0;

    private MyAdapter mAdapter;
    private List<BloodGlucoseRecord> data = new ArrayList<>();
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_glucose);

        mUnbinder = ButterKnife.bind(this);

        initRecyclerView();

        mDataUtil.getBloodGlucoseData(this, days, (BloodGlucoseDataUtil.OnPostExecute<List<BloodGlucoseRecord>>) bloodGlucoseRecords -> {
            if (bloodGlucoseRecords == null) {
                Toast.makeText(BloodGlucoseActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
                return;
            }
            for (BloodGlucoseRecord bloodGlucoseRecord : bloodGlucoseRecords) {
                for (int i = 1; i <= 8; i++) {
                    double d = bloodGlucoseRecord.getDataBySign(i);
                    dataStatus(d, true);
                }
            }
            if (mBarChartView != null) {
                mBarChartView.setDatas(new int[]{low, good, high});
            }
            data = bloodGlucoseRecords;
            if (loadingView == null) {
                return;
            }
            if (data.size() > 0) {
                loadingView.setVisibility(View.GONE);
            }
            mAdapter.setBloodGlucoseRecords(bloodGlucoseRecords);
            ObjectAnimator animator1 = ObjectAnimator.ofFloat(mCardView, "alpha", 0.5f, 1);
            ObjectAnimator animator2 = ObjectAnimator.ofFloat(mCardView, "translationX", DensityUtils.dp2px(BloodGlucoseActivity.this,-500), 0);
            ObjectAnimator animator3 = ObjectAnimator.ofFloat(mCardView, "scaleX", 0, 1);
            ObjectAnimator animator4 = ObjectAnimator.ofFloat(mCardView, "scaleY", 0, 1);
            AnimatorSet set = new AnimatorSet();
            set.setDuration(500);
            set.playTogether(animator1, animator3, animator4);
            set.start();
        });
    }

    private void dataStatus(double d, boolean isAdd) {
        int n = -1;
        if (isAdd) {
            n = 1;
        }
        if (d == 0) { // 用于剔除未输入数据，包括修改前为0的后修改后为0的数据
            return;
        }
        if (d < 4.4) {
            low+=n;
            return;
        }
        if (d >10.0) {
            high+=n;
            return;
        }
        good +=n;
    }

    private void initRecyclerView() {
        mAdapter = new MyAdapter(data);
        mAdapter.setOnItemClickListener(new OnItemClickedListener<BloodGlucoseRecord>() {
            @Override
            public void onItemClicked(View view, int index, BloodGlucoseRecord item) {
                if (index == 0 || data.size() == 0) {
                    return;
                }

                XPopup.get(BloodGlucoseActivity.this)
                        .asCustom(new MyPopup(BloodGlucoseActivity.this, new MyPopup.PopupAdapter() {

                            double preD = item.getDataBySign(index);

                            @Override
                            public void receiveData(double d) {
                                TextView textView = (TextView) view;
                                if(d == this.preD) {
                                    return;
                                }
                                BigDecimal bigDecimal = new BigDecimal(d);
                                double dd = bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

                                mDataUtil.saveBloodGlucoseData(BloodGlucoseActivity.this, item, index, d, (BloodGlucoseDataUtil.OnPostExecute<String>) s -> {
                                    if (textView == null || mBarChartView == null) {
                                        return;
                                    }
                                    if ("\"1\"".equals(s)) {
                                        setViewData(textView, dd, index);
                                        item.setDataBySign(index, dd);

                                        dataStatus(preD, false);
                                        dataStatus(d, true);
                                        mBarChartView.setDatas(new int[]{low, good, high});

                                        Toast.makeText(BloodGlucoseActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(BloodGlucoseActivity.this, "保存失败，服务器繁忙。", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public String getTitle() {
                                return mSimpleDateFormat.format(item.getRecordDate()) + "     " + DateUtils.getTimeDescription(index);
                            }

                            @Override
                            public String getNumberStr() {
                                if (preD == 0) {
                                    return "0";
                                }
                                return String.valueOf(preD);
                            }
                        }))
                        .show();
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
    }

    @OnClick(R.id.back)
    public void back() {
        this.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDataUtil != null) {
            mDataUtil.clear();
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }


    private class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        private List<BloodGlucoseRecord> mBloodGlucoseRecords;

        private OnItemClickedListener<BloodGlucoseRecord> mOnItemClickedListener;

        MyAdapter(List<BloodGlucoseRecord> bloodGlucoseRecords) {
            this.mBloodGlucoseRecords = bloodGlucoseRecords;
        }

        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            MyHolder holder = new MyHolder(LayoutInflater.from(BloodGlucoseActivity.this).inflate(R.layout.blood_glucose_one_row_layout, viewGroup,false));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
            BloodGlucoseRecord bloodGlucoseRecord = mBloodGlucoseRecords.get(i);
            Date date = bloodGlucoseRecord.getRecordDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            String str = calendar.get(Calendar.DATE) + " " + (calendar.get(Calendar.MONTH) + 1) + "月";
            SpannableString spannableString = new SpannableString(str);
            int t = str.indexOf(' ');
            int l = str.length();
            RelativeSizeSpan sizeSpan2 = new RelativeSizeSpan(0.65f);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#000000"));
            spannableString.setSpan(colorSpan, 0, t, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            spannableString.setSpan(sizeSpan2, t, l, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            myHolder.dateView.setText(spannableString);

            setViewData(myHolder.textView1, bloodGlucoseRecord.getDataBySign(1), 1);
            setViewData(myHolder.textView2, bloodGlucoseRecord.getDataBySign(2), 2);
            setViewData(myHolder.textView3, bloodGlucoseRecord.getDataBySign(3), 3);
            setViewData(myHolder.textView4, bloodGlucoseRecord.getDataBySign(4), 4);
            setViewData(myHolder.textView5, bloodGlucoseRecord.getDataBySign(5), 5);
            setViewData(myHolder.textView6, bloodGlucoseRecord.getDataBySign(6), 6);
            setViewData(myHolder.textView7, bloodGlucoseRecord.getDataBySign(7), 7);
            setViewData(myHolder.textView8, bloodGlucoseRecord.getDataBySign(8), 8);

            if (mOnItemClickedListener == null) {
                return;
            }

            myHolder.textView1.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView1, 1, bloodGlucoseRecord));
            myHolder.textView2.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView2, 2, bloodGlucoseRecord));
            myHolder.textView3.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView3, 3, bloodGlucoseRecord));
            myHolder.textView4.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView4, 4, bloodGlucoseRecord));
            myHolder.textView5.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView5, 5, bloodGlucoseRecord));
            myHolder.textView6.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView6, 6, bloodGlucoseRecord));
            myHolder.textView7.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView7, 7, bloodGlucoseRecord));
            myHolder.textView8.setOnClickListener(v -> mOnItemClickedListener.onItemClicked(myHolder.textView8, 8, bloodGlucoseRecord));
        }

        @Override
        public int getItemCount() {
            return mBloodGlucoseRecords.size();
        }

        public void setBloodGlucoseRecords(List<BloodGlucoseRecord> records) {
            this.mBloodGlucoseRecords = records;
            notifyDataSetChanged();
        }

        void setOnItemClickListener(OnItemClickedListener<BloodGlucoseRecord> listener) {
            this.mOnItemClickedListener = listener;
        }

    }


    private void setViewData(TextView textView, double data, int sign) {
        if (data == 0) {
            textView.setText("+");
            textView.setBackgroundResource(R.drawable.cell_text_view);
            return;
        }
        if (data < 4.4) {
            textView.setBackgroundResource(R.drawable.cell_text_view_low);
        } else if (data > 10.0) {
            textView.setBackgroundResource(R.drawable.cell_text_view_high);
        } else {
            textView.setBackgroundResource(R.drawable.cell_text_view_good);
        }

        textView.setText(String.valueOf(data));

    }


    private class MyHolder extends RecyclerView.ViewHolder {

        TextView dateView;
        TextView textView1;
        TextView textView2;
        TextView textView3;
        TextView textView4;
        TextView textView5;
        TextView textView6;
        TextView textView7;
        TextView textView8;

        MyHolder(@NonNull View itemView) {
            super(itemView);
            dateView = itemView.findViewById(R.id.date);
            textView1 = itemView.findViewById(R.id.text1);
            textView2 = itemView.findViewById(R.id.text2);
            textView3 = itemView.findViewById(R.id.text3);
            textView4 = itemView.findViewById(R.id.text4);
            textView5 = itemView.findViewById(R.id.text5);
            textView6 = itemView.findViewById(R.id.text6);
            textView7 = itemView.findViewById(R.id.text7);
            textView8 = itemView.findViewById(R.id.text8);
        }
    }
}
